﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.Basis
{
    /// <summary>
    /// 任务中心
    /// </summary>
    public partial class TaskCenterBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        List<OperateModel> operList;
        OperateModel oper;
        ReturnResult rsl;
        CuDbHelper cuHelper;
        Tools.TxtLogHelper txt;
        public TaskCenterBLL()
        {
            //数据交互
            cmd = new Commands();
            //当前登录人信息
            userLogin = new LoginInfo();
            cuHelper = new CuDbHelper();
            txt = new Tools.TxtLogHelper();
        }

        // 向TaskCenter添加信息
        //ReturnResult InsertInto_TaskCenter(string businessType, string contents, string toUser, string memo)
        public ReturnResult InsertInto_TaskCenter()
        {
            rsl = new ReturnResult();
            try
            {
                Summary_Restock_ChangeTag(); //汇总改标和补货任务
                Summary_Restock_inKuTask(); //入库任务汇总


                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                //switch (businessType)
                //{
                //    case "changeTag":
                //        rsl = InsertChangeTag_TaskCenter(contents, toUser, memo);
                //        break;

                //    case "restock":
                //        rsl = InsertRestock_TaskCenter(contents, toUser, memo);
                //        break;

                //    case "inKuTask":
                //        rsl = InsertInKuTask_TaskCenter(contents, toUser, memo);
                //        break;

                //    default:
                //        break;
                //}

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        // 汇总不合格并进行补货改标流程
        public void Summary_Restock_ChangeTag()
        {
            
            var sql = "select * from sys_parameters_info where parCode = 'rs_ct_config'";
            var dt = cmd.GetDataTable(sql);

            var configString = dt.Rows[0]["parValue"].ToString();
            var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);
            
            #region 需要检查现存量的仓库 、 货位
            var houseString = "'"; 
            //var posString = "";
            foreach (var house in rc_config.restock.outWarehouse)
            {
                houseString += house;
                houseString += "',";
            }
            houseString = houseString.TrimEnd(',');

            //foreach (var house in rc_config.restock.outPosition)
            //{
            //    posString +="'" +house+ "',";
            //}
            //posString = posString.TrimEnd(',');
            #endregion

            CuDbHelper cuDb = new CuDbHelper();

            // 每次统计，需要生成调拨任务的列表
            var restockList = new List<Restock_Keyword>();
            // 每次统计，需要生成改标任务的列表
            var changeTagList = new List<Restock_Keyword>();

            #region 查找不合格数据，按照存货编码、规格、颜色、商标汇总
            var sumSql = "select * from pi_restock_info where status = '0' and isdel = 0  and datatype='restock' ";
            var sumDt = cmd.GetDataTable(sumSql);

            var groupedData = sumDt.AsEnumerable().GroupBy(r => new
            {
                proCode = r.Field<string>("proCode"),
                spec = r.Field<string>("spec"),
                color = r.Field<string>("color"),
                shangbiao = r.Field<string>("shangbiao"),
            });
            #endregion

            var rids = ""; //记录相关记录表的id 

            #region 对于每组数据(每种存货)
            foreach (var data in groupedData)
            {
                var theKey = data.Key;
                var proCode = theKey.proCode;
                var color = theKey.color;
                var shangbiao = theKey.shangbiao;
                var proName = data.First()["proName"].ToString();
                var spec = data.First()["spec"].ToString();

                #region 相关记录的id
                var ids = sumDt.AsEnumerable().
                    Where(r => r.Field<string>("proCode") == proCode
                    && r.Field<string>("color") == color
                    && r.Field<string>("shangbiao") == shangbiao
                     && r.Field<string>("spec") == spec)
                    .Select(s => s).ToList();

                foreach (var s in ids)
                {
                    rids += "'" + s["id"] + "',";
                }
                #endregion

                // 数量求和
                var nSum = data.Sum(r => decimal.Parse(r["number"].ToString()));

                // 查询现存量表 CurrentStock  
                // 把每个仓库的数量，都记录下来
                // 先不做，先默认一个仓库
                //var stockSql_template = @"select * from CurrentStock where cInvCode = '{0}' 
                //                          and cFree1 = '{1}' and cFree3 = '{2}' and cWhCode in ({3})";

                // 改成查 InvPositionSum 
                var stockSql_template = @"select * from InvPositionSum where iQuantity>0 and cInvCode = '{0}' 
                                          and cFree1 = '{1}' and cFree3 = '{2}' and cWhCode in ({3}) ";  //and cPosCode in ({4})
                var stockSql = string.Format(stockSql_template, proCode, color, shangbiao, houseString); //, posString
                var stockDt = cuDb.getData(stockSql, "");

                var stockNum = 0.0m;
                // 也得加tableRow的判断
                if (stockDt.Rows.Count > 0)
                {
                    stockNum = decimal.Parse(stockDt.Rows[0]["iquantity"].ToString());
                }

                #region 根据现存量及不合格品数量判断生成的任务类型
                // 如果现存量大于不合格汇总数量
                // 向任务中心插入出库信息
                if (stockNum >= nSum)
                {
                    restockList.Add(new Restock_Keyword
                    {
                        proName = proName,
                        spec = spec,
                        color = color,
                        proCode = proCode,
                        shangbiao = shangbiao,
                        number = nSum.ToString(),
                        positionCode= stockDt.Rows[0]["cPosCode"].ToString()
                    });
                }
                // 生成改标申请单
                else
                {
                    // 如果现存量不为零
                    if (stockNum != 0.0m)
                    {
                        //将现存量生成出库任务
                        restockList.Add(new Restock_Keyword
                        {
                            proName = proName,
                            spec = spec,
                            color = color,
                            proCode = proCode,
                            shangbiao = shangbiao,
                            number = stockNum.ToString(),
                            positionCode = stockDt.Rows[0]["cPosCode"].ToString()
                        });

                        //剩余数量 = 不合格数量-现存数量
                        var remainNum = nSum - stockNum;

                        //剩余数量 生成改标任务
                        changeTagList.Add(new Restock_Keyword
                        {
                            proName = proName,
                            spec = spec,
                            color = color,
                            proCode = proCode,
                            shangbiao = shangbiao,
                            number = remainNum.ToString()
                        });
                    }
                    // 不合格数量全部生成改标任务
                    else
                    {
                        changeTagList.Add(new Restock_Keyword
                        {
                            proName = proName,
                            spec = spec,
                            color = color,
                            proCode = proCode,
                            shangbiao = shangbiao,
                            number = nSum.ToString()
                        });
                    }

                }

                #endregion
            }
            #endregion

            operList = new List<OperateModel>();
            var toUsers = "";

            #region 补货列表
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var tms = Convert.ToInt64(ts.TotalMilliseconds).ToString();
            var taskCode = getTimesString();

            // 处理补货列表
            if (restockList.Count > 0)
            {
                var restockJson = JsonConvert.SerializeObject(restockList);
                toUsers = "";
                foreach (var s in rc_config.restock.toUser)
                {
                    toUsers += s + ',';
                }
                var restockTask = new DbTaskCenter
                {
                    id = tms,
                    businessType = "restock",
                    businessId = rids,
                    //toUser = rc_config.restock.toUser,
                    toUser = toUsers.TrimEnd(','),
                    contents = restockJson,
                    createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    isFinish = 0,
                    taskCode = taskCode,
                    memo = "自动统计不合格报工中的补货信息",
                };

                oper = new OperateModel
                {
                    Types = OperateModel.OperateType.Add,
                    Data = restockTask
                };
                operList.Add(oper);
            }
            #endregion

            #region 改标列表
            ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            tms = Convert.ToInt64(ts.TotalMilliseconds).ToString();
            taskCode = getTimesString();
            // 处理改标列表
            if (changeTagList.Count > 0)
            {
                var changeTagJson = JsonConvert.SerializeObject(changeTagList);
                toUsers = "";
                foreach (var s in rc_config.changeTag.toUser)
                {
                    toUsers += s + ',';
                }
                var changeTagTask = new DbTaskCenter
                {
                    id = tms,
                    businessType = "changeTag",
                    //businessId = DateTime.Now.ToString("yyyy-MM-dd"),
                    businessId = rids,
                    //toUser = rc_config.changeTag.toUser,
                    toUser = toUsers.TrimEnd(','),
                    contents = changeTagJson,
                    createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    isFinish = 0,
                    taskCode = taskCode,
                    memo = "自动统计不合格报工中的改标信息",
                };

                oper = new OperateModel
                {
                    Types = OperateModel.OperateType.Add,
                    Data = changeTagTask
                };
                operList.Add(oper);
            }
            #endregion

            // 对处理过的数据，做标记
            foreach (DataRow row in sumDt.Rows)
            {
                var changed = new DbRestockInfo
                {
                    id = int.Parse(row["id"].ToString()),
                    status = "1"
                };

                oper = new OperateModel { Conditions = "id", Data = changed, Types = OperateModel.OperateType.Edit };
                operList.Add(oper);
            }

            // 执行
            if (operList.Count > 0)
            {
                try
                {
                    var result = cmd.MoreUpdate(operList);
                }
                catch (Exception ex)
                {
                    var c = ex.Message;
                }

            }
        }

        // 汇总入库任务
        public void Summary_Restock_inKuTask()
        {
            CuDbHelper cuDb = new CuDbHelper();

            // 查找待入库记录
            var sumSql = "select * from pi_restock_info where status = '0' and isdel = 0 and datatype='inKuTask' ";
            var sumDt = cmd.GetDataTable(sumSql);
            if (sumDt.Rows.Count < 1)
            {
                return;//没有需要汇总生成的任务
            }

            #region 仓库分组 
            var wareCodes = sumDt.AsEnumerable().GroupBy(r => new
            {
                wareCode = r.Field<string>("wareCode")
            });
            #endregion

            #region 获取仓库库管信息
            StringBuilder sb = new StringBuilder();
            sb.Append("select m.userCode,u.userName,m.groupCode from fun_Users_gangwei m ");
            sb.Append("inner join sys_users_info u on u.userCode = m.userCode and u.isDel = 0 and status = 'Y' ");
            sb.Append("where dType = 'WH'  and m.isdel=0 ");
            var uTable = cmd.GetDataTable(sb.ToString());
            #endregion

            #region 根据报工单获取报工信息
            sb.Clear();
            sb.Append("select m.userName,p.gxName,bgCode from V_Plan_BaoGong_Main m ");
            sb.Append("inner join V_GongXuPrice_info p on p.cgxCode=m.gxCode ");
            var table = cmd.GetDataTable(sb.ToString());
            #endregion


            #region 对于每个仓库
            foreach (var wh in wareCodes)
            {
                operList = new List<OperateModel>();
                var wareCode = wh.Key.wareCode;

                #region 获取通知的库管，获取不到库管直接返回
                var toUser = "wjj";//库管
                var uDatas = uTable.Select("groupCode='" + wareCode+"'");
                if (uDatas.Length > 0)
                {
                    toUser = uDatas[0]["userCode"].ToString();
                }
                else
                {
                    return;
                }
                #endregion

                #region 按存货编码、规格、颜色、商标汇总数据  groupedData
                var groupedData = sumDt.AsEnumerable().
                    Where(r => r.Field<string>("wareCode") == wh.Key.wareCode)
                       .GroupBy(r => new
                       {
                           proCode = r.Field<string>("proCode"),
                           spec = r.Field<string>("spec"),
                           color = r.Field<string>("color"),
                           shangbiao = r.Field<string>("shangbiao"),
                       });
                    //.Select(s => s).ToList();
                #endregion

                // 每次统计，需要生成任务的列表
                var inList = new List<Restock_Keyword>();
                var rids = ""; //记录相关记录表的id 
                var bgCodes = ""; //相关报工单号
                var relationPp = ""; //联系人

                #region 遍历 求和、记录id 等信息
                foreach (var data in groupedData)
                {
                    var theKey = data.Key;
                    var proCode = theKey.proCode;
                    var color = theKey.color;
                    var shangbiao = theKey.shangbiao;
                    var proName = data.First()["proName"].ToString();
                    var spec = data.First()["spec"].ToString();

                    // 数量求和
                    var nSum = data.Sum(r => decimal.Parse(r["number"].ToString()));

                    inList.Add(new Restock_Keyword
                    {
                        wareCode = wareCode,
                        proName = proName,
                        spec = spec,
                        color = color,
                        proCode = proCode,
                        shangbiao = shangbiao,
                        number = nSum.ToString()
                    });
                    
                    #region 相关记录的id
                    var ids = sumDt.AsEnumerable().
                        Where(r => r.Field<string>("wareCode") == wareCode
                        && r.Field<string>("proCode") == proCode
                         && r.Field<string>("spec") == spec
                          && r.Field<string>("color") == color
                           && r.Field<string>("shangbiao") == shangbiao)
                        .Select(s => s).ToList();

                    foreach (var s in ids)
                    {
                        rids += "'" + s["id"] + "',";
                        //lxrCode += "'" + s["toUser"] + "',";
                    }
                    #endregion

                }

                #endregion

                #region 根据报工单获取工序和报工人
                var bgTable = sumDt.Select("wareCode=" + wareCode);
                foreach (var dr in bgTable)
                {
                    bgCodes += "'" + dr["bgCode"] + "',";
                }

                var list = new List<string>();

                bgTable = table.Select("bgCode in (" + bgCodes.TrimEnd(',') + ")");
                foreach (var dr in bgTable)
                {
                    string names = dr["userName"] + "-" + dr["gxName"];
                    if (!list.Contains(names))
                    {
                        list.Add(names);
                        relationPp += names + ",";
                    }
                }
                #endregion


                #region 任务表添加记录
                var taskCode = getTimesString();

                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var tms = Convert.ToInt64(ts.TotalMilliseconds).ToString();

                var inkuJson = JsonConvert.SerializeObject(inList);
                var inkuTask = new DbTaskCenter
                {
                    id = tms,
                    businessType = "inKu",
                    businessId = rids,
                    toUser = toUser,
                    relationPeople = relationPp,
                    contents = inkuJson,
                    createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    isFinish = 0,
                    taskCode = taskCode,
                    memo = "入库任务",
                };

                oper = new OperateModel
                {
                    Types = OperateModel.OperateType.Add,
                    Data = inkuTask
                };
                operList.Add(oper);
                #endregion

                #region 对处理过的数据，做标记
                foreach (string i in rids.TrimEnd(',').Replace("'", "").Split(','))
                {
                    var changed = new DbRestockInfo
                    {
                        id = int.Parse(i),
                        status = "1"
                    };

                    oper = new OperateModel { Conditions = "id", Data = changed, Types = OperateModel.OperateType.Edit };
                    operList.Add(oper);
                }
                #endregion

                // 执行
                if (operList.Count > 0)
                {
                    try
                    {
                        var result = cmd.MoreUpdate(operList);
                    }
                    catch (Exception ex)
                    {
                        var c = ex.Message;
                    }

                }
            }

            #endregion

            
        }












        ReturnResult InsertInKuTask_TaskCenter(string contents, string toUser, string memo)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var taskCenter = new DbTaskCenter
                {
                    contents = contents,
                    toUser = toUser,
                    businessType = "changeTag",
                    businessId = getNowDate(),
                    createtime = getNow(),
                    isFinish = 0,
                    taskCode = getTimeString(),
                    memo = "自动统计不合格报工中的改标信息",

                };
                oper = new OperateModel();
                oper.Data = taskCenter;
                oper.Types = OperateModel.OperateType.Add;

                operList.Add(oper);
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        ReturnResult InsertChangeTag_TaskCenter(string contents, string toUser, string memo)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var taskCode = getTimeString();
                var taskCenter = new DbTaskCenter
                {
                    id = taskCode,
                    contents = contents,
                    toUser = toUser,
                    businessType = "changeTag",
                    businessId = getNowDate(),
                    createtime = getNow(),
                    isFinish = 0,
                    taskCode = taskCode,
                    memo = "自动统计不合格报工中的改标信息",

                };
                oper = new OperateModel();
                oper.Data = taskCenter;
                oper.Types = OperateModel.OperateType.Add;

                operList.Add(oper);
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        ReturnResult InsertRestock_TaskCenter(string contents, string toUser, string memo)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var taskCode = getTimeString();
                var taskCenter = new DbTaskCenter
                {
                    id = taskCode,
                    contents = contents,
                    toUser = toUser,
                    businessType = "restock",
                    businessId = getNowDate(),
                    createtime = getNow(),
                    isFinish = 0,
                    taskCode = taskCode,
                    memo = "自动统计不合格报工中的补货信息",

                };
                oper = new OperateModel();
                oper.Data = taskCenter;
                oper.Types = OperateModel.OperateType.Add;

                operList.Add(oper);
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        // 获取TaskCenter列表？

        // 向pi_restock_info添加信息


    }

    public partial class TaskCenterBLL : PubMethod
    {
        public ReturnResult InsertInto_RestockInfo(string dataType, string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                switch (dataType)
                {
                    case "Restock_ChangeTag":
                        rsl = Restock_ChangeTag_RestockInfo(jsonStr);
                        break;

                    case "":
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult Restock_ChangeTag_RestockInfo(string contents)
        {
            var objList = JsonConvert.DeserializeObject<List<Object>>(contents);
            return null;
        }
    }
}
